const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

const configPath = path.join(__dirname, 'config');
const keyPath = path.join(configPath, 'server.key');
const csrPath = path.join(configPath, 'server.csr');
const crtPath = path.join(configPath, 'server.crt');

function generateCertificate() {
    try {
        // 生成私钥
        execSync(`openssl genrsa -out ${keyPath} 2048`);
        console.log('Private key generated.');

        // 生成证书签名请求（CSR）
        execSync(`openssl req -new -key ${keyPath} -out ${csrPath} -subj "/C=US/ST=California/L=San Francisco/O=Your Company/OU=Your Unit/CN=localhost"`);
        console.log('Certificate signing request generated.');

        // 生成自签名证书
        execSync(`openssl x509 -req -days 365 -in ${csrPath} -signkey ${keyPath} -out ${crtPath}`);
        console.log('Self-signed certificate generated.');
    } catch (error) {
        console.error('Error generating certificate:', error);
    }
}

function deleteCertificate() {
    try {
        if (fs.existsSync(keyPath)) fs.unlinkSync(keyPath);
        if (fs.existsSync(csrPath)) fs.unlinkSync(csrPath);
        if (fs.existsSync(crtPath)) fs.unlinkSync(crtPath);
        console.log('Certificates deleted.');
    } catch (error) {
        console.error('Error deleting certificates:', error);
    }
}

function queryCertificate() {
    try {
        const output = execSync(`openssl x509 -in ${crtPath} -noout -dates`).toString();
        console.log('Certificate validity period:');
        console.log(output);
    } catch (error) {
        console.error('Error querying certificate:', error);
    }
}

function main() {
    const args = process.argv.slice(2);
    if (args.length === 0) {
        console.log('Usage: node manage-certificates.js <option>');
        console.log('Options:');
        console.log('  1 - Generate/Update certificate');
        console.log('  2 - Delete certificate');
        console.log('  3 - Query certificate validity period');
        return;
    }

    const option = args[0];
    switch (option) {
        case '1':
            generateCertificate();
            break;
        case '2':
            deleteCertificate();
            break;
        case '3':
            queryCertificate();
            break;
        default:
            console.log('Invalid option. Please use 1, 2, or 3.');
    }
}

main();